package com.lc.user.express.ordermanagement;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lc.user.express.BaseSecondActivity;
import com.lc.user.express.R;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetOrderCancel;
import com.lc.user.express.httpserver.GetOrderChoosed;
import com.lc.user.express.utils.GetToast;
import com.lc.user.express.utils.PublicMethod;
import com.lc.user.express.view.dialog.AffirmDialog;
import com.zcx.helper.http.AsyCallBack;

/**
 * Created by Administrator on 2016/4/14.订单管理派单中详情
 */
public class OrderSendingDetailsActivity extends BaseSecondActivity implements AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter {
    public static final String SHOW_SELECT_DIVER = "com.lc.user.express.details.show.select.diver";
    private BroadcastReceiver mReceiver;
    private AMap aMap;
    private MapView mapView;

    private TextView tv_driver_name, tv_driver_disc;//地址
    private SimpleDraweeView riv_head;// 头像
    private Marker marker;
    private LatLng slatLng;//发货地位置
    private LatLng dlatLng;//司机位置
    private TextView tv_status;//订单派单中
    private String mobile;//手机号
    private ImageView iv_call;//call

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_sending_details);
        initView();
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        init();
        registerReceiver();
    }

    private void initView() {
        setTitle("正在派单");
        setRightButtonText("取消订单", 150);
        tv_driver_name = (TextView) findViewById(R.id.tv_driver_name);
        tv_driver_disc = (TextView) findViewById(R.id.tv_driver_disc);
        riv_head = (SimpleDraweeView) findViewById(R.id.riv_head);
        iv_call = (ImageView) findViewById(R.id.iv_call);
        iv_call.setOnClickListener(this);
        //ImageManager.from(cnt).displayImage(riv_head, "", R.mipmap.default_pic);
        // riv_head.setImageURI(Uri.parse(""));

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.head_right:
                new AffirmDialog(cnt, "您确定要取消该订单吗？", "取消", "确定", R.style.MyDialog) {

                    @Override
                    protected void onYesClick() {
                        // TODO Auto-generated method stub
                        cancelOrder();
                    }
                }.show();
                break;
            case R.id.iv_call:
                if (!TextUtils.isEmpty(mobile)) {
                    PublicMethod.callPhone(cnt, mobile);
                } else {
                    GetToast.useString(cnt, "暂无电话号码");
                }
                break;
        }
    }

    private void cancelOrder() {
        new GetOrderCancel(AppContext.myPreferences.getUid(), getIntent().getStringExtra("orderid"), new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object info) throws Exception {
                super.onSuccess(toast, type, info);
                if (OrderManagementFragment.onRefreshOrderData != null) {
                    OrderManagementFragment.onRefreshOrderData.onRefresh();
                }
                finish();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);//调接口
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.getUiSettings().setZoomControlsEnabled(false);//隐藏放大缩小按钮
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.moveCamera(CameraUpdateFactory.zoomTo(12));
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式

        String s = getIntent().getStringExtra("spoint");
        if (TextUtils.isEmpty(s)) {
            return;
        }
        String[] ss = s.split(",");
        slatLng = new LatLng(PublicMethod.strToDouble(ss[0]), PublicMethod.strToDouble(ss[1]));
        marker = aMap.addMarker(new MarkerOptions()
                .position(slatLng)
                .icon(BitmapDescriptorFactory.fromBitmap(
                        BitmapFactory.decodeResource(getResources(), R.mipmap.addr_start))));
        marker.setTitle("正在派单");
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(slatLng));
        marker.showInfoWindow();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        orderChoosed();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }


    @Override
    public View getInfoContents(Marker marker) {

        return null;
    }

    /**
     * 监听自定义infowindow窗口的infowindow事件回调
     */
    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(
                R.layout.map_window_sending_order, null);
        AppContext.ScaleScreenHelper.loadView((ViewGroup) infoWindow);
        tv_status = (TextView) infoWindow.findViewById(R.id.tv_status);
        LinearLayout ll_order = (LinearLayout) infoWindow.findViewById(R.id.ll_order);
        ll_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("orderid", getIntent().getStringExtra("orderid"));
                show(OrderDetailsActivity.class, bundle);
            }
        });
        return infoWindow;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
//        ToastUtil.show(this, "你点击了infoWindow窗口" + marker.getTitle());
    }


    private void registerReceiver() {
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                String action = intent.getAction();
                if (action == null) {
                    return;
                }
                if (action.equals(SHOW_SELECT_DIVER)) {
                    orderChoosed();
                }
            }
        };

        // 动态注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SHOW_SELECT_DIVER);
        registerReceiver(mReceiver, intentFilter);
    }

    private void orderChoosed() {
        new GetOrderChoosed(getIntent().getStringExtra("orderid"), AppContext.myPreferences.getUid(), new AsyCallBack<GetOrderChoosed.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetOrderChoosed.Info info) throws Exception {
                super.onSuccess(toast, type, info);
                setTitle("派单中");
//                iv_call.setVisibility(View.VISIBLE);
                iv_call.setVisibility(View.GONE);
                tv_driver_name.setText(info.name);
                tv_driver_disc.setText("近期服务" + info.number + "次 " + info.city + " " + info.license);
                //  ImageManager.from(cnt).displayImage(riv_head, info.avatar, R.mipmap.default_pic);
            /* Glide.with(mContext)
                        .load(info.avatar)
                        .placeholder(R.drawable.shape_background) // can also be a drawable
                        .error( R.mipmap.default_pic) // will be displayed if the image cannot be loaded
                        .crossFade()
                        .into(riv_head);*/
                riv_head.setImageURI(Uri.parse(info.avatar));
                Log.d("-------------", info.avatar);

                mobile = info.mobile;

                if (aMap == null) {//清空地图
                    return;
                }

                aMap.clear();
                String s = info.point;
                String[] ss = s.split(",");
                dlatLng = new LatLng(PublicMethod.strToDouble(ss[0]), PublicMethod.strToDouble(ss[1]));//司机经纬度

                marker = aMap.addMarker(new MarkerOptions()
                        .position(dlatLng)
                        .icon(BitmapDescriptorFactory.fromResource(R.mipmap.cars)));//标注司机位置
                marker.setTitle("司机");
                aMap.addMarker(new MarkerOptions()
                        .position(slatLng)
                        .icon(BitmapDescriptorFactory.fromBitmap(
                                BitmapFactory.decodeResource(getResources(), R.mipmap.addr_start))));//标注发货地址位置

                marker.showInfoWindow();
                tv_status.setText("司机正在赶往发货地址");
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(dlatLng));
                aMap.moveCamera(CameraUpdateFactory.zoomTo(11));
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }
        }).execute(cnt);//调接口
    }
}
